package com.atguigu.hadoop.examples.mapreduce.wordStandardDeviation;


import com.google.common.base.Charsets;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class WordStandardDeviation extends Configured implements Tool {
    private double stddev = 0.0D;

    public static final Text LENGTH = new Text("length");
    public static final Text SQUARE = new Text("square");
    public static final Text COUNT = new Text("count");

    public static final LongWritable ONE = new LongWritable(1L);

    private double readAndCalcStdDev(Path path, Configuration conf)
            throws IOException {
        FileSystem fs = FileSystem.get(conf);
        Path file = new Path(path, "part-r-00000");

        if (!fs.exists(file)) {
            throw new IOException("Output not found!");
        }
        double stddev = 0.0D;
        BufferedReader br = null;
        try {
            br = new BufferedReader(new InputStreamReader(fs.open(file), Charsets.UTF_8));
            long count = 0L;
            long length = 0L;
            long square = 0L;
            String line;
            while ((line = br.readLine()) != null) {
                StringTokenizer st = new StringTokenizer(line);

                String type = st.nextToken();

                if (type.equals(COUNT.toString())) {
                    String countLit = st.nextToken();
                    count = Long.parseLong(countLit);
                } else if (type.equals(LENGTH.toString())) {
                    String lengthLit = st.nextToken();
                    length = Long.parseLong(lengthLit);
                } else if (type.equals(SQUARE.toString())) {
                    String squareLit = st.nextToken();
                    square = Long.parseLong(squareLit);
                }
            }

            double mean = length / count;

            mean = Math.pow(mean, 2.0D);
            double term = square / count;
            stddev = Math.sqrt(term - mean);
            System.out.println("The standard deviation is: " + stddev);
        } finally {
            if (br != null) {
                br.close();
            }
        }
        return stddev;
    }

    public static void main(String[] args) throws Exception {

        ToolRunner.run(new Configuration(), new WordStandardDeviation(), args);
    }

    public int run(String[] args) throws Exception {
        if (args.length != 2) {
            System.err.println("Usage: wordstddev <in> <out>");
            return 0;
        }

        Configuration conf = super.getConf();

        Job job = Job.getInstance(conf, "word stddev");
        job.setJarByClass(WordStandardDeviation.class);
        job.setMapperClass(WordStandardDeviationMapper.class);
        job.setCombinerClass(WordStandardDeviationReducer.class);
        job.setReducerClass(WordStandardDeviationReducer.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(LongWritable.class);
        FileInputFormat.addInputPath(job, new Path(args[0]));
        Path outputpath = new Path(args[1]);
        FileOutputFormat.setOutputPath(job, outputpath);
        boolean result = job.waitForCompletion(true);

        this.stddev = readAndCalcStdDev(outputpath, conf);

        return result ? 0 : 1;
    }

    public double getStandardDeviation() {
        return this.stddev;
    }


}